<?php

namespace App\Tasks;

use App\Clients\MeiTuan\BillingReconciliationAllocationSettlementBills;
use App\Clients\MeiTuan\ReportsBusinessIncome;
use App\Models\MallDateFinance;
use App\Models\ProjectMall;
use DateTime;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;

class MeiTuanBusinessTimePeriodTask extends MeiTuanMallTask
{

    /**
     * @throws Exception
     * @throws GuzzleException
     */
    public function execute(): void
    {
        $this->dateData();
    }

    /**
     * @throws Exception
     * @throws GuzzleException
     */
    protected function dateData(): void
    {
        $startDate = $this->maxDate(10);
        $diffDate = (strtotime(date("Y-m-d",time())) - strtotime(date("Y-m-d",strtotime($startDate)))) / 86400;
        $queryDates = [];
        $subDate = null;
        $pmall = ProjectMall::query()->where("merchant_no",$this->mall->merchant_no)->first();

        foreach (range(0,$diffDate,1) as $index=>$item){
            $beginDate = date("Y-m-d 00:00:00",strtotime($startDate) + 1 * $index * 86400);
            $endDate = strtotime($beginDate) + 86399;
            $endDate = date("Y-m-d H:i:s",$endDate);
            $queryDates[] = [
                "startDate"=>(int) (strtotime($beginDate) * 1000),
                "endDate"=>(int) (strtotime($endDate) * 1000),
//                "startDate"=>$beginDate,
//                "endDate"=>$endDate,
                "withMoreData"=>1,
                "beforeCorss"=>1,
                "afterCorss"=>1,
                "historyRefund"=>1,
                "unckoutOrderPay"=>1,
                "otherStlmnt"=>1,
                "chargebackRefund"=>1,
                "pageNo"=>1,
                "pageSize"=>20,
                "loginName"=>$this->mall->name,
                "permissionCode"=>983,
            ];
        }

        foreach ($queryDates as $queryDate){

            $udate = date("Y-m-d",$queryDate["startDate"] / 1000);
            $model = MallDateFinance::query()
                ->where("merchant_no",$this->mall->merchant_no)
                ->where("date",$udate)
                ->first();
            if(!empty($model) && $model->is_update == 1){
                continue;
            }

            var_dump(date("Y-m-d",$queryDate["startDate"] / 1000));
            $updates = [];
            $postData = [
                "reqJson"=>json_encode($queryDate)
            ];
            $client = new ReportsBusinessIncome($this->account);
            $response = $client->execute($postData)->contents();
            $postData = [
                "billPeriodStartTime"=>$queryDate["startDate"],
                "billPeriodEndTime"=>$queryDate["endDate"],
                "pageNo"=>1,
                "pageSize"=>10,
                "poiIds"=>[$this->mall->poi_id],
            ];
            $settledAmountSum = 0;
            if($this->account->is_meituan_sync != 2){
                $client = new BillingReconciliationAllocationSettlementBills($this->account);
                $responseBill = $client->execute($postData)->contents();
                if($responseBill === false && $this->account->is_meituan_sync != 2){
                    $this->account->is_meituan_sync = 0;
                    $this->account->save();
                    break;
                }
                if(empty($this->mall->sub_merchant_id)){
                    $settledAmountSum = round($responseBill["sum"]["settledAmountSum"] / 100,2);
                }else{
                    foreach ($responseBill["pageItems"] as $pageItem){
                        if(!in_array($pageItem["merchantList"][0]["merchantId"],$this->mall->sub_merchant_id)) continue;
                        $settledAmountSum += $pageItem["actualAmount"] / 100;
                    }
                    $settledAmountSum = round($settledAmountSum,2);
                }

                if($settledAmountSum > 0 && empty($this->account->mall->sub_date)){
                    $this->account->mall->sub_date = date("Y-m-d",(int) ($queryDate["startDate"] / 1000));
                    $this->account->mall->save();
                }
            }else{
                if(!empty($pmall) && $pmall->sub_account_rate > 0){
                    $settledAmountSum = round(round($response["saleIncomeProfitAmt"] / 100,2) * $pmall->sub_account_rate / 100,2);
                }
            }
//            var_dump($settledAmountSum);
//            exit();
            $updates[] = [
                "merchant_no"=>$this->mall->merchant_no,
                "date"=>date("Y-m-d",(int) ($queryDate["startDate"] / 1000)),
                "income"=>round($response["saleIncomeProfitAmt"] / 100,2),//
                "settle_money"=>$settledAmountSum,
                "bill_no"=>empty($responseBill["pageItems"]) ?  "" : $responseBill["pageItems"][0]["allocationBillNo"],
            ];
            DB::beginTransaction();
            try{
                MallDateFinance::query()->upsert($updates,["merchant_no","date"],["income","settle_money","bill_no"]);
                $this->account->date_sync_at = date("Y-m-d");
                $this->account->save();
                DB::commit();
            }catch (Exception $e){
                DB::rollBack();
                throw $e;
            }
        }
        if(!empty($this->account->mall->sub_date) && $this->account->is_meituan_sync != 2){
            MallDateFinance::query()
                ->where("merchant_no",$this->mall->merchant_no)
                ->where("date","<", $this->account->mall->sub_date)
                ->delete();
        }
        $this->updateIncom();

    }
}
